package com.thread.prodcustrom;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;

public class TestBlockQueueConsumerAndProducer {

	/*最大生成数量*/
	static int MAX_NUM = 10;
	private static LinkedBlockingDeque mBlockQueue = new LinkedBlockingDeque<Integer>(MAX_NUM);


	public static void main(String args[]) {
		//创建一个生产者
		new Thread(new Producer()).start();

		//创建两个消费者
		new Thread(new Consumer()).start();
		//创建两个消费者
		new Thread(new Consumer()).start();
	}

	static class Producer implements Runnable {
		public void product() {
			while (true) {
				if (mBlockQueue.peek() == null) {
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					for (int i = 1; i <= 10; i++) {
						try {
							mBlockQueue.put(i);
							System.out.println("Producer now product num:" + i);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
				}
			}
		}

		@Override
		public void run() {
			product();
		}
	}

	static class Consumer implements Runnable {
		public void consume() {
			while (true) {
				try {
					Thread.sleep(500);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				Integer mLast = (Integer) mBlockQueue.peekLast();
				if (mLast != null && mLast == MAX_NUM) {
					try {
						int num = (Integer) mBlockQueue.take();
						System.out.println(new StringBuilder(Thread.currentThread().getName())
								.append(" Consumer now consumption num:").append(num));
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}

			}
		}

		@Override
		public void run() {
			consume();
		}
	}
}
